package com.ashin.dp;

import java.util.Arrays;

/**
 * @Author: Ashin
 * @Date: 2020/9/27
 * @Description: com.ashin
 * @Version: 1.0.0
 */
public class MaxSubAarray {

    public static void main(String[] args) {
        // 1. 初始化状态
        int[] values = {-2, 1, -3, 1, -1, 6, 2, -5, 4};
        System.out.println(max(values));
        System.out.println(maxSubArray(values));
    }


    public static int max(int[] values) {
        //初始状态
        if (values.length < 0) {
            return 0;
        }
        int[] dp = new int[values.length];
        dp[0] = values[0];
        int max = values[0];
        for (int valIdx = 1; valIdx < values.length; valIdx++) {
            dp[valIdx] = Math.max(dp[valIdx - 1] + values[valIdx], values[valIdx]);


            max = Math.max(max, dp[valIdx]);
        }
        System.out.println(Arrays.toString(dp));

        return max;
    }

    public static int maxSubArray(int[] nums) {
        int[] dp = new int[nums.length];
        int maxSum = nums[0];
        dp[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            //因为只需要记住前一个状态，所以这里是可以优化为一个变量来取代dp数组，这里是为了和老师课程dp示范呼应
            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
            maxSum = Math.max(maxSum, dp[i]);
        }
        return maxSum;
    }
}
